package com.zhou.common.lib.serilizer;

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.xerial.snappy.Snappy;

/**
 * @author li.ke
 * @date 2021/12/7
 */
public class SnappyRedisSerializer<T> implements RedisSerializer<T> {
    private KryoSerializer<T> kryoSerializer;

    public SnappyRedisSerializer(KryoSerializer<T> kryoSerializer) {
        this.kryoSerializer = kryoSerializer;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException {
        try {
            byte[] bytes = kryoSerializer.serialize(t);
            return Snappy.compress(bytes);
        } catch (Exception ex) {
            throw new SerializationException(ex.getMessage());
        }
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        try {
            byte[] raw = Snappy.uncompress(bytes);
            return kryoSerializer.deserialize(raw);
        } catch (Exception ex) {
            throw new SerializationException(ex.getMessage());
        }
    }
}
